﻿using EMall.Application;
using EMall.IdentityService.Menus;
using EMall.Uow;
using Microsoft.EntityFrameworkCore;

namespace EMall.IdentityService.PermissionGrants
{
    public class PermissionGrantAppService : ApplicationService, IPermissionGrantAppService
    {
        private readonly IPermissionGrantRepository _permissionGrantRepository;
        public PermissionGrantAppService(
            IPermissionGrantRepository permissionGrantRepository)
        {
            _permissionGrantRepository = permissionGrantRepository;
        }

        [UnitOfWork]
        public async Task SetPermissionsAsync(SetPermissionsDto input)
        {
            var permissions = input.Permissions.SplitToList();
            var keys = input.Keys.SplitToList();
            var exsitingPermissions = await QueryService.GetQueryable<PermissionGrant>()
                .Where(o => o.Type == input.Type && keys.Contains(o.Key))
                .ToListAsync();
            var deletePermissions = exsitingPermissions.Where(o => !permissions.Contains(o.Permission));
            foreach (var permission in deletePermissions)
            {
                await _permissionGrantRepository.RemoveAsync(permission);
            }
            var addPermissions = permissions.Where(o => !exsitingPermissions.Select(s => s.Permission).Contains(o));
            foreach (var permission in addPermissions)
            {
                foreach (var key in keys)
                {
                    var permissionGrant = new PermissionGrant(permission, input.Type, key);
                    await _permissionGrantRepository.AddAsync(permissionGrant);
                }
            }
        }
        public async Task<IEnumerable<string>> GetPermissionsAsync(GetPermissionsQueryDto input)
        {
            var keys = input.Keys.SplitToList();
            return await QueryService.GetQueryable<PermissionGrant>()
                .Where(o => o.Type == input.Type && keys.Contains(o.Key))
                .Select(o => o.Permission)
                .ToListAsync();
        }
    }
}